<template>
  <base-breadcrumb :title="$route.meta.title">
    <div class="page-detail">
      <template>
        <a-card v-loading="loading">
          <title-name title="风险信息" />
          <!-- 表单列 -->
          <custom-form ref="customForm" :form="form1" :edit-model="step === 1 && !isComment ? 'E' : 'V'" :form-list="formList" :rules="form1Rules" is-validate @search="handleOpen" @click="handleOpen">
            <!-- 风险级别 -->
            <template #riskLevel>
              <a-radio-group v-model="form1.riskLevel" style="width: calc(100% + 96px); margin: 60px 0 0 -96px" :disabled="isComment || step !== 1" @change="handleChange">
                <div :style="radioStyle">
                  <a-radio :value="1"> 一般风险 </a-radio>
                  <BaseTextarea
                    v-model="form1.generalRisk"
                    :class="{ defaultForm: form1.riskLevel !== 1 }"
                    :max-length="1000"
                    style="width: 100%"
                    :disabled="isDisableRisk || isComment || step !== 1"
                    @change="$refs.customForm.validateField('riskLevel')"
                  />
                </div>
                <div :style="radioStyle">
                  <a-radio :value="2"> 较大风险 </a-radio>
                  <BaseTextarea
                    v-model="form1.greaterRisk"
                    :max-length="1000"
                    :class="{ defaultForm: form1.riskLevel !== 2 }"
                    style="width: 100%"
                    :disabled="isDisableRisk || isComment || step !== 1"
                    @change="$refs.customForm.validateField('riskLevel')"
                  />
                </div>
                <div :style="radioStyle">
                  <a-radio :value="3"> 重大风险 </a-radio>
                  <BaseTextarea
                    v-model="form1.majorRrisk"
                    :max-length="1000"
                    :class="{ defaultForm: form1.riskLevel !== 3 }"
                    style="width: 100%"
                    :disabled="isDisableRisk || isComment || step !== 1"
                    @change="$refs.customForm.validateField('riskLevel')"
                  />
                </div>
              </a-radio-group>
            </template>
            <!-- 责任部门 -->
            <template #orgId>
              <div style="margin-top: -3px">
                <span v-show="form1.orgName || form1.orgId" class="mr20">{{ form1.orgName || form1.orgId }}</span>
                <a-button v-if="step === 1 && !isComment" @click="selectDepartmentVisible = true"> 选择部门 </a-button>
              </div>
            </template>
          </custom-form>
        </a-card>
        <!-- 工作要求 -->
        <a-card v-if="step != 1 || isComment">
          <title-name title="工作要求" />
          <a-table :data-source="form1.workContent ? [form1] : []" row-key="id" :columns="columnsWork" :pagination="false" />
        </a-card>
        <!-- 批注 -->
        <comments v-if="isComment" :id="form1.id" />
        <!-- 风险处理 -->
        <risk v-if="step === 2" :id="form1.id" />
        <!-- 风险销项 -->
        <a-card v-if="form1.salesAuditStatus && !isComment && step !== 2">
          <title-name title="风险销项" />
          <a-form-model ref="form2Rules" :model="form2" :rules="form2Rules">
            <a-row>
              <a-col span="24">
                <a-form-model-item label="证明附件" prop="fileList">
                  <a v-if="form1.riskSalesBusVO.fileInfoVO.fileName" :href="$fileUrl(form1.riskSalesBusVO.fileInfoVO)"> {{ form1.riskSalesBusVO.fileInfoVO.fileName }}</a>
                  <div v-else style="margin-top: -3px">无</div>
                </a-form-model-item>
              </a-col>
              <a-col span="24">
                <a-form-model-item label="销项说明" prop="xxxDes">
                  <div>{{ form1.riskSalesBusVO.salesContent || '无' }}</div>
                  <!-- <b-textarea v-model="form1.riskSalesBusVO.salesContent" disabled /> -->
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="销项人">
                  <div>{{ form1.riskSalesBusVO.creatorName || '无' }}</div>
                  <!-- <b-input
                    :value="form1.riskSalesBusVO.creatorName"
                    disabled
                  /> -->
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="销项时间">
                  <div v-if="form1.riskSalesBusVO.modifiedTime">
                    {{ form1.riskSalesBusVO.modifiedTime | dateFormat }}
                  </div>
                  <div v-else style="margin-top: -3px">无</div>
                  <!-- <b-input :value="form1.riskSalesBusVO.modifiedTime | dateFormat" disabled /> -->
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </a-card>
        <!-- 相关附件 -->
        <a-card>
          <title-name title="相关附件" />
          <u-table :is-show="!isComment && step === 1" business-code="LCM10" :is-upload="false" :file-arrys.sync="form1.fileInfoVO" :upload-arrys="uploadArrys" />
        </a-card>
      </template>
      <div class="tar page-btn-right-top">
        <template v-if="!isComment">
          <a-button v-if="isShowOptions && step === 1" type="primary" :loading="loading" class="mr10p" @click="submit"> 提交 </a-button>
          <!-- <a-button v-if="isShowOptions && step === 1" type="primary" :loading="loading" @click="save" class="mr10p"
            >保存
          </a-button> -->
        </template>
        <a-button @click="$close"> 关闭 </a-button>
      </div>
    </div>
    <!-- 选择要素库风险弹窗 -->
    <a-modal title="选择要素库风险" :visible="elementCheckListVisible" class="large-modal" :footer="null" @cancel="elementCheckListVisible = false" @ok="elementCheckListVisible = false">
      <b-table ref="table" :columns="columns" :request="loadData">
        <span slot="index" slot-scope="text, record, index">{{ index + 1 }}</span>
        <template slot="time" slot-scope="text, record">
          {{ record.createTime | dateFormat }}
        </template>
        <template slot="auditStatusStr" slot-scope="text, record">
          <list-status :status="record.auditStatus" :text="text" />
        </template>
        <template slot="operation" slot-scope="text, record">
          <div class="pub-table-list-action">
            <span @click="chooseRow(record)">选择</span>
          </div>
        </template>
      </b-table>
    </a-modal>
    <!-- 选择部门 -->
    <SelectDepartment
      :visible.sync="selectDepartmentVisible"
      :level="form1.riskLevel ? ['PD', 'BC', 'CO'][form1.riskLevel - 1] : ''"
      @ok="
        form1.orgId = $event.id
        form1.orgName = $event.label
      "
    />
  </base-breadcrumb>
</template>

<script>
import riskListApi from '@/api/legal/risk/list'

import SelectSubCompany from '@/components/Select/SelectSubCompany'
import SelectProject from '@/components/Select/SelectProject'
import comments from '@/views/Legal/risk/list/components/comments'
import risk from '@/views/Legal/risk/list/components/risk'
import SelectDepartment from '@/components/Dialog/SelectDepartment'
import elementCheckListApi from '@/api/legal/risk/elementCheckList'
import moment from 'moment'
import { checkCostAnalysisAudit } from '@/api/businessAffairs/revenueAndCost'
import { projectCycleEarlyWarnChangeStatus } from '@/api/legal/risk/periodRisk'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置

export default {
  name: 'RiskListAdd',
  extends: new BaseEditPage(),
  components: {
    comments,
    risk,
    SelectDepartment
  },
  data() {
    const validator = (rule, value, callback) => {
      if (!value) {
        callback(new Error('风险级别不能为空'))
      } else if (value === 1 && !this.form1.generalRisk) {
        callback(new Error('一般风险备注不能为空'))
      } else if (value === 2 && !this.form1.greaterRisk) {
        callback(new Error('较大风险备注不能为空'))
      } else if (value === 3 && !this.form1.majorRrisk) {
        callback(new Error('重大风险备注不能为空'))
      } else {
        callback()
      }
      // if (!value) {
      //   callback(new Error('风险级别不能为空'))
      // } else if (!this.form1.generalRisk || !this.form1.greaterRisk || !this.form1.majorRrisk) {
      //   callback(new Error('风险备注不能为空'))
      // } else {
      //   callback()
      // }
    } // 风险级别校验
    return {
      elementCheckListVisible: false,
      selectDepartmentVisible: false,
      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          scopedSlots: { customRender: 'index' }
        },
        {
          title: '风险名称',
          dataIndex: 'riskName',
          width: 160
        },
        {
          title: '责任部门',
          dataIndex: 'orgName',
          width: 150
        },
        {
          title: '创建人',
          dataIndex: 'creatorName',
          width: 150
        },

        {
          title: '创建时间',
          dataIndex: 'createTime',
          scopedSlots: { customRender: 'time' },
          width: 120
        },
        {
          title: '状态',
          dataIndex: 'auditStatusStr',
          scopedSlots: { customRender: 'auditStatusStr' },
          width: this.STATUS_WIDTH
        },
        {
          title: '操作',
          width: 100,
          fixed: 'right',
          scopedSlots: { customRender: 'operation' }
        }
      ], // 风险要素表头
      columnsWork: [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          customRender() {
            return arguments[2] + 1
          }
        },
        {
          title: '工作要求',
          ellipsis: true,
          dataIndex: 'workContent'
        },
        {
          title: '责任人',
          dataIndex: 'personLiableName'
        },
        {
          title: '完成时限',
          dataIndex: 'processingTime'
        },
        {
          title: '抄送人',
          dataIndex: 'personCCName'
        }
      ], // 工作要求表头
      loadData: (params) => {
        params.auditStatus = 'PAST'
        return elementCheckListApi.findListByMain({}, Object.assign(params, this.queryParam))
      },

      radioStyle: {
        display: 'flex',
        'align-items': 'center',
        'margin-bottom': '10px'
      },
      loading: false,
      step: 2,
      uploadArrys: [],
      form1: {
        riskSalesBusVO: {
          fileInfoVO: {}
        },
        fileInfoVO: [],
        branchCompanyId: void 0,
        projectId: void 0,
        orgId: void 0,
        orgName: void 0,
        riskName: void 0,
        riskContent: void 0,
        generalRisk: void 0,
        greaterRisk: void 0,
        majorRrisk: void 0,
        createTime: '',
        haveRiskFactors: false,
        riskLevel: null,
        branchPname: ''
      },
      form1Rules: {
        riskName: { required: true, message: '风险名称不能为空', trigger: 'change' },
        orgId: { required: true, message: '责任部门不能为空', trigger: 'change' },
        branchCompanyId: { required: true, message: '所属分公司能为空', trigger: 'change' },
        projectId: { required: true, message: '所属项目不能为空', trigger: 'change' },
        riskContent: { required: true, message: '风险描述不能为空', trigger: 'change' },
        riskLevel: { required: true, validator: validator, trigger: 'change' }
      },
      form2: {},
      form2Rules: {
        xxxDes: { required: true, message: '销项说明不能为空', trigger: 'blur' }
      },
      isInit: true,
      isComment: false,
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null 
    }
  },
  watch: {
    'form1.haveRiskFactors'(val) {
      if (this.isInit) {
        this.form1.riskName = ''
        this.form1.orgName = ''
        this.form1.riskContent = ''
        this.form1.generalRisk = ''
        this.form1.greaterRisk = ''
        this.form1.majorRrisk = ''
        this.form1.orgId = ''
        this.form1.branchPname = ''
      }
    }
  },
  computed: {
    // 表单列表配置项
    formList() {
      return [
        {
          label: '所属单位',
          type: 'orgTree',
          keyName: 'projectId',
          span: 16,
          isAutoSelectFirst: true,
          isNeedAuth: true,
          checkStrictly: true,
          disabled: this.isComment || this.step !== 1,
          // isNoBorder: false,
          // viewName: 'branchPname',
          hidden: this.isHideLoss,
          rules: [{ required: true, message: '请选择', trigger: 'change' }]
        },
        // {
        //   type: SelectSubCompany,
        //   keyName: 'branchCompanyId',
        //   viewName: 'branchCompany',
        //   label: '所属分公司',
        //   disabled: this.isComment || this.step !== 1,
        //   hidden: this.isHideLoss
        // },
        // {
        //   type: SelectProject,
        //   keyName: 'projectId',
        //   viewName: 'project',
        //   label: '项目名称',
        //   disabled: this.isComment || this.step !== 1,
        //   attrs: {
        //     isClear: false,
        //     isEdit: true,
        //     keyValue: 'branchCompanyId'
        //   },
        //   hidden: this.isHideLoss
        // },

        // { type: 'BaseInput', keyName: 'branchCompanyName', label: '所属分公司', hidden: !this.isHideLoss, disabled: true },
        // { type: 'BaseInput', keyName: 'projectName', label: '项目名称', hidden: !this.isHideLoss, disabled: true },

        {
          type: 'a-radio-group',
          keyName: 'haveRiskFactors',
          label: '是否风险要素库风险',
          disabled: this.isComment || this.step !== 1 || this.isHideLoss,
          data: [
            {
              value: true,
              label: '是'
            },
            {
              value: false,
              label: '否'
            }
          ],
          customRender() {
            return arguments[0] ? '是' : '否'
          }
        },
        {
          type: 'BaseInput',
          keyName: 'riskName',
          label: '风险名称',
          disabled: this.isComment || this.step !== 1,
          hidden: this.form1.haveRiskFactors
        },
        {
          type: 'a-input-search',
          keyName: 'riskName',
          label: '风险名称',
          disabled: this.isComment || this.step !== 1,
          hidden: !this.form1.haveRiskFactors
        },
        {
          type: 'BaseTextarea',
          keyName: 'riskContent',
          label: '风险描述',
          disabled: this.isDisableRisk || this.isComment || this.step !== 1,
          attrs: {
            maxLength: 1000
          },
          span: 24
        },
        {
          slot: true,
          keyName: 'riskLevel',
          label: '风险级别',
          span: 24
        },
        {
          slot: true,
          keyName: 'orgId',
          label: '责任部门',
          span: 24
        },
        {
          type: 'BaseInput',
          keyName: 'creatorName',
          label: '创建人',
          disabled: true
        },
        {
          type: 'BaseInput',
          keyName: 'createTime',
          label: '创建时间',
          disabled: true
          //   customRender: (e) => {
          //     return e ? this.$dateFormat(e, 'D') : '无'
          //   }
        }
      ]
    },
    isShowOptions() {
      return !this.form1.auditStatus || this.form1.auditStatus !== 'SUBMITTED'
      // return (!this.form1.auditStatus) || this.form1.auditStatus === 'DRAFT' || this.form1.auditStatus === 'REJECTED'
    },
    isDisableRisk() {
      return this.form1.haveRiskFactors
    }
  },
  async created() {
    if (this.$route.query.id) {
      this.isInit = false
      this.form1.id = this.$route.query.id
      await this.getBaseInfo()
      let res2 = await this.getFileList()
      if (res2.code === this.SUCCESS_CODE) {
        this.uploadArrys = res2.data
      }
    } else {
      let { name, phone } = this.$userInfo().employee
      this.form1.creatorName = name
      this.form1.creatorPhone = phone
      this.form1.createTime = this.$dateFormat(Date.now(), 'D')
    }
    if (this.$route.query.step) {
      this.step = Number(this.$route.query.step)
    } else {
      this.step = 1
    }

    if (this.$route.query.hideLossId && !this.isPeriodRisk) {
      //是否是工期预警
      this.isHideLoss = true
      this.getHideLoss()
    }
    //工期预警 赋值
    if (this.isPeriodRisk) {
      this.isHideLoss = true
      let row = this.$route.query
      this.form1.riskLevel = row.warnLevel * 1 + 1 //那边返回的是0,1,2这个要1,2,3,
      this.form1.branchPname = row.branchName + '/' + row.projectName
      this.form1.branchCompanyId = row.branchId
      this.form1.branchCompanyName = row.branchName
      this.form1.projectId = row.projectId
      this.form1.projectName = row.projectName
      this.form1.riskName = '工期风险'
      this.form1.riskContent = row.warnInfo
      let msg = `${row.warnLevelName}风险`
      switch (this.form1.riskLevel) {
        case 1:
          this.form1.generalRisk = msg
          break
        case 2:
          this.form1.greaterRisk = msg
          break
        case 3:
          this.form1.majorRrisk = msg
          break
        default:
          break
      }
    }

    this.isComment = Number(this.$route.query.isComment) === 1
  },
 async mounted() {
    this.$route.meta.title = this.$route.query.id ? '风险列表详情' : '风险列表新增'
        //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('legal_risk_law')  
  },
  methods: {
    //获取潜亏风险
    async getHideLoss() {
      let row = this.$route.query
      this.loading = true
      const [err, res] = await checkCostAnalysisAudit({ id: this.$route.query.hideLossId })
      this.loading = false
      if (!err) {
        this.form1.riskName = new moment(row.monthDate).format('YYYY年MM月') + '-潜亏风险'
        let temp = new moment(res.data.monthDate).format('YYYY年MM月') + '\n'
        // res.data.itemList.map(v => {
        //   if (v.name.search('') !== -1) {
        //     temp += `${v.name}:${Math.floor((v.cumulativeThisPeriod / 10000) * 100) / 100}万元\n`
        //   }
        //   if (v.name.search('率') === -1) {
        //     temp += `${v.name}:${Math.floor((v.cumulativeThisPeriod / 10000) * 100) / 100}万元\n`
        //   } else {
        //     temp += `${v.name}:${v.cumulativeThisPeriod}\n`
        //   }
        // })
        temp += '工程计量确权(不含税)：' + row.confirmationRight + '万元\n'
        temp += '截止目前项目实际产值(不含税)：' + row.projectActOutPutValueSoFar + '万元\n'
        temp += '截止目前项目实际成本(不含税)：' + row.projectActCostSoFar + '万元\n'
        temp += '工程计量确认率：' + row.confirmationRate + '(%)'
        this.form1.riskContent = temp
        this.form1.branchCompanyId = res.data.branchComId
        this.form1.branchPname = this.$route.query.branchComName + '/' + this.$route.query.projectName
        this.form1.branchCompanyName = this.$route.query.branchComName
        this.form1.projectId = res.data.projectId
        this.form1.projectName = this.$route.query.projectName
        // console.log(res.data)
        // this.form = res.data
      }
    },
    /**
     * @description:风险级别发生改变
     */
    handleChange() {
      this.form1.orgId = void 0
      this.form1.orgName = void 0
    },
    /**
     * @description:获取文件列表
     */
    getFileList() {
      return riskListApi.getFileList({}, { businessId: this.form1.id })
    },
    /**
     * @description:打开要素库风险
     * @param {*} name 表单单名
     */
    handleOpen(name) {
      name === 'riskName' && this.form1.haveRiskFactors && (this.elementCheckListVisible = true)
    },
    /**
     * @description: 选中风险要素
     * @param {*} row
     */
    chooseRow(row) {
      this.form1.riskName = row.riskName
      //   this.form1.orgName = row.orgName
      //   this.form1.orgId = row.orgId
      this.form1.riskContent = row.riskContent
      this.form1.generalRisk = row.generalRisk
      this.form1.greaterRisk = row.greaterRisk
      this.form1.majorRrisk = row.majorRrisk
      this.elementCheckListVisible = false
    },
    /**
     * @description: 获取基础数据
     */
    async getBaseInfo() {
      this.loading = true
      let res = await riskListApi.findListByMainId({}, { id: this.form1.id })
      if (res.code === this.SUCCESS_CODE) {
        this.form1 = res.data
        if (!this.form1.riskSalesBusVO) {
          this.form1.riskSalesBusVO = { fileInfoVO: {} }
        }
        setTimeout(() => (this.isInit = true), 0)
      }
      this.loading = false
    },
    /**
     * @description: 保存
     * @return {Promise}
     */
    save() {
      return new Promise(async (resolve) => {
        if (this.step == 1) {
          this.loading = true
          let res
          // 设置为无风险状态
          this.form1.auditStatus = 'DRAFT'
          // 重置未选中风险级别备注
          switch (this.form1.riskLevel) {
            case 1:
              this.form1.greaterRisk = void 0
              this.form1.majorRrisk = void 0
              break
            case 2:
              this.form1.generalRisk = void 0
              this.form1.majorRrisk = void 0
              break
            case 3:
              this.form1.greaterRisk = void 0
              this.form1.generalRisk = void 0
              break
            default:
              break
          }
          // 添加公司id
          this.form1.companyId = this.$userInfo()?.employee?.levels?.find((item) => item.code === 'CO')?.id
          // 添加项目部id参数
          this.form1.projectOrgId = this.$currentPost()?.id
          // 格式化文件列表
          this.form1.fileInfoVO?.length > 0 && (this.form1.fileIds = this.form1.fileInfoVO.map((item) => item.commonId).join())
          if (this.form1.id) {
            res = await riskListApi.editByRisk(this.form1)
          } else {
            res = await riskListApi.createByRisk(this.form1)
          }
          if (res.code === 200) {
            // this.$message.success('保存成功')
            this.form1.id = res.data.id
            resolve(true)
            // this.getBaseInfo()
          }
          this.loading = false
          resolve(false)
        }
      })
    },
    /**
     * @description: 提交表单
     */
    async submit(status) {
      this.setProcessConfig = null;   
      this.$refs.customForm.validate(async (valid) => {
        if (valid) {
        this.submitApprovalConfirm(status =='SUBMITTED'?this.processConfig:6, async (flag)=>{
          if(!flag) {
            this.loading = false
            return
          }
          this.$submitConfirm(async () => {
            if (!(await this.save())) {
              return
            }
            this.loading = true
            let res = await riskListApi.riskSubmit({
              baseId: this.form1.id,
              //   auditStatusEnum: 'SUBMITTED',
              type: this.step
            })
            if (res.code === 200) {
              this.$noticeSuccess('提交成功')
              if (this.isHideLoss && !this.isPeriodRisk) {
                //非工期预警变成已转化
                await riskListApi.legalEditById({}, { id: this.$route.query.hideLossId })
              }
              if (this.isHideLoss && this.isPeriodRisk) {
                // 工期预警变成已转化
                await projectCycleEarlyWarnChangeStatus({ id: this.$route.query.hideLossId })
              }
              //   this.$router.push({ path: 'index' })
                //console.log(res,12222)
               this.$close()
            }
            this.loading = false
          })
          })
        } else {
          this.$noticeWarning('请填写完整')
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .ant-form-item {
  .ant-form-item-label {
    width: 160px;
  }

  .ant-form-item-control-wrapper {
    width: calc(100% - 160px);
  }
}

/deep/ .defaultForm .ant-input:not([disabled]) {
  border-color: #d9d9d9;
  background-color: #fff;
}
</style>
